// Copyright 2021 by 马万里. All rights reserved.
// 开发团队 ：   鸡中之霸
// 开发人员 ：   马万里
// 开发时间 ：   2021/2/24 16:45
// 文件名称 ：   user.go
// 工程名称 ：   netpan
// 开发工具 ：   GoLand
//

package db

import (
	"fmt"
	myDB "johnsonsmile.cn/netpan/db/mysql"
)

// UserSignUp: 向mysql插入注册的用户信息
func UserSignUp(username string, password string) bool {
	stmt, err := myDB.DBConn().Prepare(
		"INSERT INTO tbl_user(`user_name`, `user_pwd`) VALUES (?,?)",
	)
	if err != nil {
		fmt.Printf("Failed to create statement, err: %s\n", err)
		return false
	}
	defer stmt.Close()
	ret, err := stmt.Exec(username, password)
	if err != nil {
		fmt.Printf("Failed to insert, err: %s\n", err)
		return false
	}
	if rowsAffected, err := ret.RowsAffected(); err == nil && rowsAffected > 0 {
		return true
	}
	return false
}

// UserSignIn: 向mysql查询用户信息
func UserSignIn(username string, password string) bool {
	stmt, err := myDB.DBConn().Prepare(
		"SELECT `user_name` FROM tbl_user WHERE user_name = ? AND user_pwd = ? LIMIT 1",
	)
	if err != nil {
		fmt.Printf("Failed to create statement, err: %s\n", err)
		return false
	}
	defer stmt.Close()

	rows, err := stmt.Query(username, password)
	if err != nil {
		fmt.Println(err.Error())
		return false
	}
	if rows == nil {
		fmt.Println("username not found: " + username)
		return false
	}
	return true
}

// UpdateToken: 更新token
func UpdateToken(username string, token string) bool {
	stmt, err := myDB.DBConn().Prepare(
		"REPLACE INTO tbl_user_token (`user_name`, `user_token`) VALUES (?, ?)",
	)
	if err != nil {
		fmt.Printf("Failed to create statement, err: %s\n", err)
		return false
	}
	defer stmt.Close()
	_, err = stmt.Exec(username, token)
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

type User struct {
	Username     string
	Email        string
	Phone        string
	SignupAt     string
	LastActiveAt string
	Status       int
}

// GetUserInfo: 获取用户信息
func GetUserInfo(username string) (*User, error) {
	user := User{}
	stmt, err := myDB.DBConn().Prepare(
		"SELECT user_name, signup_at FROM tbl_user WHERE user_name = ? LIMIT 1",
	)
	if err != nil {
		fmt.Printf("Failed to create statement, err: %s\n", err)
		return nil, err
	}
	defer stmt.Close()

	// 执行查询操作
	err = stmt.QueryRow(username).Scan(&user.Username, &user.SignupAt)
	if err != nil {
		return nil, err
	}
	return &user, err
}
